package main

import (
	"iot-base/common/dbconn"
	"strconv"
)

func alarmQuery(qmap map[string]string) ([]map[string]interface{}, error) {
	tid := qmap["tid"]
	aid := qmap["aid"]
	sindex := qmap["index"]
	sBegin := qmap["begintime"]
	sEnd := qmap["endtime"]
	ip := qmap["ip"]
	bi := qmap["bi"]
	sel := "select alarm_histroys.* ,thing_params.param_value as ip,things.* "
	tables := " from alarm_histroys ,thing_params,things "
	where := " where alarm_histroys.is_hide = false and thing_params.thing_id = alarm_histroys.t_id and  thing_params.param_id in ('IP','ip') "
	where += " and things.uid = alarm_histroys.t_id "
	if ip != "" {
		sel += " ,thing_params.param_value as ip"
		//tables += " ,thing_params"
		where += (` and thing_params.param_value like '%` + ip + "%'")
	}
	if bi != "" {

		where += (` and things.business_id like '%` + bi + "%'")
	}

	if sindex != "-1" {
		_, err := strconv.ParseInt(sindex, 10, 64)
		if err == nil {
			where = where + " and alarm_histroys.mindex=" + sindex
		}

	}
	if tid != "" {
		where = where + " and alarm_histroys.t_id='" + tid + "'"
	}
	if aid != "" {
		where = where + " and alarm_histroys.alarm_id='" + aid + "'"
	}

	if sBegin != "" {
		where = where + " and alarm_histroys.alarm_time >='" + sBegin + "'"
	}
	if sEnd != "" {
		where = where + " and alarm_histroys.alarm_time <='" + sEnd + "'"
	}

	var result []map[string]interface{}
	sql := sel + tables + where + " order by alarm_histroys.alarm_time desc"
	err := dbconn.DBConnection.Raw(sql).Find(&result).Error
	return result, err
}
